package com.katze.boot.plugins.shiro.authentication;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.katze.boot.common.utils.SpringContextUtils;
import com.katze.boot.plugins.shiro.ShiroProperties;
import com.katze.boot.system.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class JWTUtils {
    private static final Logger log = LoggerFactory.getLogger(JWTUtils.class);

    public static final long EXPIRE_TIME = SpringContextUtils.getBean(ShiroProperties.class).getJwtTimeOut() * 1000;



    /**
     * 从 token中获取用户名
     *
     * @return token中包含的用户名
     */
    public static <T>T getUserId(String token, Class<T> c) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").as(c);
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 生成 token
     *
     * @param user 用户
     * @return token
     */
    public static String sign(User user) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
            return JWT.create()
                    .withClaim("id", user.getUserId())
                    .withClaim("username", user.getUsername())
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("生成 token异常", e);
            return null;
        }
    }
}
